import React, { useState } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  Image,
  FlatList,
  StyleSheet,
} from "react-native";
import { useTheme } from "@/contexts/ThemeContext";
import { Ionicons } from "@expo/vector-icons";
import { Avatar, CheckBox } from "@rneui/themed";
import QRCode from "react-native-qrcode-svg";
import { saveFileToGallery } from "@/utils/file-utils";
import BottomSheet from "@/components/Global/BottomSheet";
import { Friend } from "@/types/friend";

export type ShareContentType = "group" | "personal" | "message";

interface SharePanelProps {
  visible: boolean;
  onClose: () => void;
  type?: ShareContentType;
  contentId?: string;
  contentName?: string;
  contentAvatar?: string;
  contentDescription?: string;
}

/**
 * @author BelovedLYC
 * @description 通用分享/转发面板组件
 * 通用分享/转发面板组件
 * 支持多选好友
 * 支持保存二维码
 * 支持发送给选中的好友
 * 支持切换标签页
 * 支持切换多选模式
 * 支持切换好友列表
 * 支持切换二维码
 */
const SharePanel: React.FC<SharePanelProps> = ({
  visible,
  onClose,
  type = "group",
  contentId,
  contentName,
  contentAvatar,
  contentDescription,
}) => {
  const { colors } = useTheme();
  const [activeTab, setActiveTab] = useState<"qrcode" | "friends">(
    type === "message" ? "friends" : "qrcode"
  );
  const qrCodeRef = React.useRef<any>(null);
  const [isMultiSelect, setIsMultiSelect] = useState(false);
  const [selectedFriends, setSelectedFriends] = useState<string[]>([]);

  // 模拟数据 - 实际应用中应该从store获取
  const mockData = {
    group: {
      id: contentId || "group123456",
      name: contentName || "技术交流群",
      avatar:
        contentAvatar ||
        [
          "https://randomuser.me/api/portraits/men/32.jpg",
          "https://randomuser.me/api/portraits/women/44.jpg",
          "https://randomuser.me/api/portraits/men/22.jpg",
          "https://randomuser.me/api/portraits/women/28.jpg",
        ][Math.floor(Math.random() * 4)],
      description:
        contentDescription || "这是一个技术交流群，欢迎加入讨论技术话题",
      memberCount: 56,
      owner: {
        id: "user123",
        name: "张三",
        avatar: "https://randomuser.me/api/portraits/men/1.jpg",
      },
      createTime: "2023-05-15T10:30:00Z",
    },
    personal: {
      id: contentId || "user789012",
      name: contentName || "李四",
      avatar: contentAvatar || "https://randomuser.me/api/portraits/men/43.jpg",
      description: contentDescription || "个人简介：热爱技术，喜欢分享",
    },
    message: {
      id: contentId || "msg456789",
      name: contentName || "消息摘要",
      avatar: contentAvatar || "https://randomuser.me/api/portraits/men/22.jpg",
      description: contentDescription || "这是一条重要消息，请查看...",
    },
  };

  // 根据类型获取当前内容数据
  const getCurrentContent = () => {
    return mockData[type] || mockData.group;
  };

  const currentContent = getCurrentContent();

  // 模拟好友列表数据
  const mockFriends: Friend[] = [
    {
      id: "f1",
      uuid: "uuid1",
      nickname: "张三",
      remark: "老张",
      avatar: "https://randomuser.me/api/portraits/men/32.jpg",
      friendStatus: 1,
      lastOnlineTime: new Date().toISOString(),
      createTime: new Date().toISOString(),
    },
    {
      id: "f2",
      uuid: "uuid2",
      nickname: "李四",
      remark: "",
      avatar: "https://randomuser.me/api/portraits/women/44.jpg",
      friendStatus: 0,
      lastOnlineTime: new Date().toISOString(),
      createTime: new Date().toISOString(),
    },
    {
      id: "f3",
      uuid: "uuid3",
      nickname: "王五",
      remark: "老王",
      avatar: "https://randomuser.me/api/portraits/men/43.jpg",
      friendStatus: 1,
      lastOnlineTime: new Date().toISOString(),
      createTime: new Date().toISOString(),
    },
    {
      id: "f4",
      uuid: "uuid4",
      nickname: "赵六",
      remark: "",
      avatar: "https://randomuser.me/api/portraits/women/21.jpg",
      friendStatus: 0,
      lastOnlineTime: new Date().toISOString(),
      createTime: new Date().toISOString(),
    },
    {
      id: "f5",
      uuid: "uuid5",
      nickname: "陈七",
      remark: "小陈",
      avatar: "https://randomuser.me/api/portraits/men/22.jpg",
      friendStatus: 1,
      lastOnlineTime: new Date().toISOString(),
      createTime: new Date().toISOString(),
    },
  ];

  // 保存二维码到相册
  const saveQRCodeToGallery = async () => {
    if (qrCodeRef.current) {
      await qrCodeRef.current.toDataURL(async (dataURL: string) => {
        await saveFileToGallery(dataURL);
      });
    }
  };

  // 处理好友选择
  const handleSelectFriend = (friend: Friend) => {
    if (isMultiSelect) {
      // 多选模式下，切换选中状态
      setSelectedFriends((prev) => {
        if (prev.includes(friend.id)) {
          return prev.filter((id) => id !== friend.id);
        } else {
          return [...prev, friend.id];
        }
      });
    } else {
      // 单选模式下，直接分享
      console.log(`分享${type}给${friend.nickname}: ${currentContent.id}`);
      onClose();
    }
  };

  // 切换多选模式
  const handleToggleMultiSelect = () => {
    setIsMultiSelect(!isMultiSelect);
    // 清空已选择的好友
    setSelectedFriends([]);
  };

  // 发送给选中的好友
  const handleSendToSelected = () => {
    if (selectedFriends.length === 0) return;
    const selectedNicknames = mockFriends
      .filter((friend) => selectedFriends.includes(friend.id))
      .map((friend) => friend.nickname)
      .join(", ");

    console.log(
      `分享${type}给${selectedFriends.length}位好友(${selectedNicknames}): ${currentContent.id}`
    );
    onClose();
  };
  // 获取二维码值
  const getQRValue = () => {
    switch (type) {
      case "group":
        return `telechat://groupchat?id=${
          currentContent.id
        }&name=${encodeURIComponent(currentContent.name || "")}`;
      case "personal":
        return `telechat://user?id=${
          currentContent.id
        }&name=${encodeURIComponent(currentContent.name || "")}`;
      case "message":
        return `telechat://message?id=${currentContent.id}`;
      default:
        return `telechat://unknown`;
    }
  };

  // 获取标题文本
  const getTitleText = () => {
    switch (type) {
      case "group":
        return "群聊分享";
      case "personal":
        return "个人名片";
      case "message":
        return "消息分享";
      default:
        return "分享";
    }
  };

  // 获取ID标签文本
  const getIdLabel = () => {
    switch (type) {
      case "group":
        return `群号: ${currentContent.id}`;
      case "personal":
        return `用户ID: ${currentContent.id}`;
      default:
        return "";
    }
  };

  // 渲染不同的内容
  const renderContent = () => {
    return (
      <View style={{ flex: 1 }}>
        {/* 标签页切换 - 仅在非消息类型时显示 */}
        {type !== "message" ? (
          <View style={styles.tabsContainer}>
            <TouchableOpacity
              style={[styles.tab, activeTab === "qrcode" && styles.activeTab]}
              onPress={() => setActiveTab("qrcode")}
            >
              <Text
                style={[
                  styles.tabText,
                  { color: colors.text.secondary },
                  activeTab === "qrcode" && { color: colors.primary },
                ]}
              >
                二维码
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.tab, activeTab === "friends" && styles.activeTab]}
              onPress={() => setActiveTab("friends")}
            >
              <Text
                style={[
                  styles.tabText,
                  { color: colors.text.secondary },
                  activeTab === "friends" && { color: colors.primary },
                ]}
              >
                好友
              </Text>
            </TouchableOpacity>
          </View>
        ) : null}

        {/* 内容区域 */}
        {activeTab === "qrcode" ? (
          <ScrollView>
            <View style={styles.qrCodeContainer}>
              <View style={styles.avatarContainer}>
                <Avatar
                  source={{ uri: currentContent.avatar }}
                  size={80}
                  rounded
                  containerStyle={styles.avatar}
                />
                <Text style={[styles.name, { color: colors.text.primary }]}>
                  {currentContent.name}
                </Text>
                {!!currentContent.id && (
                  <Text
                    style={[styles.idLabel, { color: colors.text.secondary }]}
                  >
                    {getIdLabel()}
                  </Text>
                )}
              </View>

              {currentContent.description && (
                <Text
                  style={[styles.description, { color: colors.text.secondary }]}
                >
                  {currentContent.description}
                </Text>
              )}

              <View style={styles.qrContainer}>
                <QRCode
                  getRef={(ref) => (qrCodeRef.current = ref)}
                  value={getQRValue()}
                  size={200}
                  logo={{ uri: currentContent.avatar }}
                  logoSize={40}
                  logoBackgroundColor="white"
                  logoMargin={2}
                  logoBorderRadius={20}
                />
              </View>

              <View style={styles.actionsContainer}>
                <TouchableOpacity
                  style={[
                    styles.actionButton,
                    { backgroundColor: colors.primary },
                  ]}
                  onPress={saveQRCodeToGallery}
                >
                  <Text style={styles.actionText}>保存二维码</Text>
                </TouchableOpacity>
              </View>
            </View>
          </ScrollView>
        ) : (
          <View style={{ flex: 1 }}>
            {/* 显示已选择的好友数量 */}
            {isMultiSelect && selectedFriends.length > 0 && (
              <View
                style={[
                  styles.selectionInfo,
                  { borderBottomColor: colors.border.divider },
                ]}
              >
                <Text style={{ color: colors.text.secondary }}>
                  已选择 {selectedFriends.length} 人
                </Text>
              </View>
            )}

            {/* 好友列表 */}
            <FlatList
              data={mockFriends}
              keyExtractor={(item) => item.id}
              style={{ flex: 1 }}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={[
                    styles.friendItem,
                    { borderBottomColor: colors.border.divider },
                  ]}
                  onPress={() => handleSelectFriend(item)}
                >
                  {isMultiSelect && (
                    <CheckBox
                      checked={selectedFriends.includes(item.id)}
                      onPress={() => handleSelectFriend(item)}
                      containerStyle={styles.checkbox}
                      checkedColor={colors.primary}
                    />
                  )}
                  <Avatar
                    rounded
                    size={50}
                    source={{ uri: item.avatar }}
                    containerStyle={styles.friendAvatar}
                  />
                  <View style={styles.friendInfo}>
                    <Text
                      style={[
                        styles.friendName,
                        { color: colors.text.primary },
                      ]}
                    >
                      {item.nickname}
                      {item.remark ? (
                        <Text
                          style={[
                            styles.friendRemark,
                            { color: colors.text.secondary },
                          ]}
                        >
                          （{item.remark}）
                        </Text>
                      ) : null}
                    </Text>
                    <Text
                      style={[
                        styles.friendStatus,
                        { color: colors.text.secondary },
                      ]}
                    >
                      {item.friendStatus === 1 ? "在线" : "离线"}
                    </Text>
                  </View>
                </TouchableOpacity>
              )}
            />

            {/* 多选模式下的发送按钮 */}
            {isMultiSelect && selectedFriends.length > 0 && (
              <View style={styles.sendButtonContainer}>
                <TouchableOpacity
                  style={[
                    styles.sendButton,
                    { backgroundColor: colors.primary },
                  ]}
                  onPress={handleSendToSelected}
                >
                  <Ionicons
                    name="send"
                    size={20}
                    color="#FFFFFF"
                    style={styles.sendIcon}
                  />
                  <Text style={styles.sendButtonText}>
                    发送给 {selectedFriends.length} 位好友
                  </Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
        )}
      </View>
    );
  };

  // 获取底部面板标题
  const getSheetTitle = () => {
    const baseTitle = getTitleText();
    // 在好友标签页和多选模式下，显示已选择的好友数量
    if (
      activeTab === "friends" &&
      isMultiSelect &&
      selectedFriends.length > 0
    ) {
      return `${baseTitle} (已选${selectedFriends.length}人)`;
    }
    return baseTitle;
  };

  return (
    <BottomSheet
      visible={visible}
      onClose={onClose}
      title={getSheetTitle()}
      content={renderContent()}
      hideCancel={false}
      cancelText="取消"
      contentStyle={{ padding: 0 }}
      showMultiSelect={activeTab === "friends"} // 只在好友标签页显示多选按钮
      multiSelectText={isMultiSelect ? "取消多选" : "多选"}
      onMultiSelect={handleToggleMultiSelect}
    />
  );
};

const styles = StyleSheet.create({
  tabsContainer: {
    flexDirection: "row",
    borderBottomWidth: 1,
    borderBottomColor: "#E0E0E0",
    marginBottom: 16,
  },
  tab: {
    flex: 1,
    paddingVertical: 12,
    alignItems: "center",
  },
  activeTab: {
    borderBottomWidth: 2,
    borderBottomColor: "#007AFF",
  },
  tabText: {
    fontSize: 16,
  },
  qrCodeContainer: {
    alignItems: "center",
    padding: 16,
  },
  avatarContainer: {
    marginBottom: 16,
    alignItems: "center",
  },
  avatar: {
    marginBottom: 8,
  },
  name: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 4,
  },
  idLabel: {
    fontSize: 14,
    marginBottom: 20,
  },
  description: {
    fontSize: 14,
    marginBottom: 16,
    textAlign: "center",
    paddingHorizontal: 20,
  },
  qrContainer: {
    padding: 20,
    backgroundColor: "#FFFFFF",
    borderRadius: 8,
    marginBottom: 20,
  },
  actionsContainer: {
    flexDirection: "row",
    justifyContent: "center",
    marginTop: 16,
  },
  actionButton: {
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 20,
    marginHorizontal: 8,
  },
  actionText: {
    color: "#FFFFFF",
    fontWeight: "500",
  },
  selectionInfo: {
    padding: 10,
    paddingHorizontal: 16,
    borderBottomWidth: 0.5,
    alignItems: "center",
  },
  friendItem: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderBottomWidth: 0.5,
  },
  checkbox: {
    padding: 0,
    marginRight: 5,
    backgroundColor: "transparent",
    borderWidth: 0,
  },
  friendAvatar: {
    marginRight: 12,
  },
  friendInfo: {
    flex: 1,
  },
  friendName: {
    fontSize: 16,
    fontWeight: "500",
  },
  friendRemark: {
    fontSize: 14,
    fontWeight: "normal",
  },
  friendStatus: {
    fontSize: 12,
    marginTop: 2,
  },
  sendButtonContainer: {
    padding: 16,
    borderTopWidth: 0.5,
    borderTopColor: "#E0E0E0",
  },
  sendButton: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 12,
    borderRadius: 8,
  },
  sendIcon: {
    marginRight: 8,
  },
  sendButtonText: {
    color: "#FFFFFF",
    fontSize: 16,
    fontWeight: "500",
  },
});

export default SharePanel;
